package view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.example.xuegengwang.xuegengwang.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;


import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;
import utils.BitmapUtils;
import utils.MyLogUtils;

import static android.R.attr.bitmap;

/**
 * Created by Administrator on 2017/3/18.
 * 查看图片
 */

public class MyImageCheckedView extends Dialog {
    private Context context;
    private MyViewPager topic_dialog_viewPager;
    private ArrayList<View> viewContainter = new ArrayList<>();
    private PagerAdapter adapter;
    private List<String> urls = new ArrayList<>();
    private int x, y;
    private int currentPosition;//当前选中的图片
    private List<String> realList = new ArrayList<>();//原图
    private View view;
    private LinearLayout mNumLayout;
    private ImageView currentdoc;//当前点所在的位置

    private static final String TAG = "MyImageCheckedView";

    public MyImageCheckedView(Context context) {
        super(context);
        this.context = context;
    }

    public MyImageCheckedView(Context context, int themeResId, List<String> urls, int position) {
        super(context, themeResId);
        this.context = context;
        this.urls = urls;
        currentPosition = position;
    }

    public MyImageCheckedView(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        this.context = context;
    }

    public void init(int x, int y) {
        //以view的方式引入，然后回调activity方法，setContentView，实现自定义布局
        view = LayoutInflater.from(context).inflate(R.layout.topic_dialog, null);
        realList = changeUrl(this.urls);//去缩略
        setContentView(view);
        Window dialogWindow = getWindow();
        WindowManager manager = ((Activity) context).getWindowManager();
        WindowManager.LayoutParams params = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);//设置对话框位置
        Display d = manager.getDefaultDisplay(); // 获取屏幕宽、高度
        params.width = d.getWidth();
        params.height = d.getHeight();
        this.x = x;
        this.y = y;
        params.x = x;
        params.y = y;
        dialogWindow.setAttributes(params);
        mNumLayout = (LinearLayout) view.findViewById(R.id.topic_dialog_doc_layout);
        topic_dialog_viewPager = (MyViewPager) view.findViewById(R.id.topic_dialog_viewPager);
        adapter = new PagerAdapter() {
            //viewpager中的组件数量
            @Override
            public int getCount() {
                return viewContainter.size();
            }

            //滑动切换的时候销毁当前的组件
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(viewContainter.get(position));
            }

            //每次滑动的时候生成的组件
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(viewContainter.get(position));
                return viewContainter.get(position);
            }

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public int getItemPosition(Object object) {
                return super.getItemPosition(object);
            }
        };
        topic_dialog_viewPager.setAdapter(adapter);
        initData();
        topic_dialog_viewPager.setOffscreenPageLimit(9);

        topic_dialog_viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (currentdoc != null) {
                    currentdoc.setImageResource(R.mipmap.main_doc1);
                }
                ImageView imageView = (ImageView) mNumLayout.getChildAt(position);
                imageView.setImageResource(R.mipmap.main_doc);
                currentdoc = imageView;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        topic_dialog_viewPager.setCurrentItem(currentPosition);
        if (urls.size() > 1) {
            //默认显示第一张的时候要手动把点加上去
            if (currentPosition == 0) {
                if (currentdoc != null) {
                    currentdoc.setImageResource(R.mipmap.main_doc1);
                }
                ImageView imageView = (ImageView) mNumLayout.getChildAt(0);
                imageView.setImageResource(R.mipmap.main_doc);
                currentdoc = imageView;
//            adapter.notifyDataSetChanged();
            }
        }
    }

    private void initData() {
        final Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
        final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.main_doc);
        Bitmap bitmap1 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.main_doc1);
        for (int i = 0; i < urls.size(); i++) {
            ImageView bt = new ImageView(context);
            bt.setLayoutParams(new ViewGroup.LayoutParams(bitmap.getWidth(), bitmap.getHeight()));
            bt.setImageBitmap(bitmap1);
            if (urls.size() > 1) {
                mNumLayout.addView(bt);
            }
            View view = LayoutInflater.from(context).inflate(R.layout.topic_dialog_item, null);
            final RelativeLayout topic_dialog_item_layout = (RelativeLayout) view.findViewById(R.id.topic_dialog_item_layout);
            final PhotoView topic_dialog_item_photoView = (PhotoView) view.findViewById(R.id.topic_dialog_item_photoView);
            final RelativeLayout topic_dialog_item_layout2 = (RelativeLayout) view.findViewById(R.id.topic_dialog_item_layout2);
            final PhotoView topic_dialog_item_photoView2 = (PhotoView) view.findViewById(R.id.topic_dialog_item_photoView2);
            topic_dialog_item_photoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            topic_dialog_item_photoView2.setScaleType(ImageView.ScaleType.FIT_CENTER);
            final RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) topic_dialog_item_layout.getLayoutParams();
            params.leftMargin = x;
            params.topMargin = y;
            params.height = 180;
            params.width = 180;
            topic_dialog_item_layout.setLayoutParams(params);
            MyImageLoader.showImage(urls.get(i), topic_dialog_item_photoView);
            final int finalI = i;
            final int scale = 20;

            final Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case 1:
                            //点开
                            if (msg.arg1 != 1) {
                                int max = display.getWidth() < display.getHeight() ? display.getWidth() : display.getHeight();
                                max = (int) ((float) max / 4) - 180;
                                params.height = params.height + max / scale;
                                params.width = params.width + max / scale;
                                params.leftMargin = params.leftMargin + ((display.getWidth() / 2) - 90 - x) / scale - ((max / 2) / scale);
                                params.topMargin = params.topMargin + ((display.getHeight() / 2) - 90 - y) / scale - ((max / 2) / scale);

                                topic_dialog_item_layout.setLayoutParams(params);
                            } else {
                                if (realList.size() > 0 && realList.size() >= finalI) {
                                    MyImageLoader.showImage(realList.get(finalI), topic_dialog_item_photoView2, new ImageLoadingListener() {
                                        @Override
                                        public void onLoadingStarted(String imageUri, View view) {

                                        }

                                        @Override
                                        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                                        }

                                        @Override
                                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                                            topic_dialog_item_layout2.setVisibility(View.VISIBLE);
                                        }

                                        @Override
                                        public void onLoadingCancelled(String imageUri, View view) {

                                        }
                                    });
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            };

            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < scale + 1; i++) {
                        Message message = new Message();
                        message.what = 1;
                        if (i == scale - 1) {
                            message.arg1 = 1;
                        }
                        handler.sendMessage(message);
                        try {
                            Thread.sleep(15);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();

            topic_dialog_item_photoView2.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
                @Override
                public void onViewTap(View view, float x, float y) {
                    MyImageCheckedView.this.dismiss();
                }
            });
            topic_dialog_item_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyImageCheckedView.this.dismiss();
                }
            });
            topic_dialog_item_layout2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyImageCheckedView.this.dismiss();
                }
            });
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyImageCheckedView.this.dismiss();
                }
            });
            viewContainter.add(view);
        }
        adapter.notifyDataSetChanged();
    }

    private void recycleBitmap() {
        for (int i = 0; i < urls.size(); i++) {
            Drawable drawable = ((PhotoView) viewContainter.get(i).findViewById(R.id.topic_dialog_item_photoView)).getDrawable();
            BitmapUtils.recycleBitmap(drawable);
            Drawable drawable1 = ((PhotoView) viewContainter.get(i).findViewById(R.id.topic_dialog_item_photoView2)).getDrawable();
            BitmapUtils.recycleBitmap(drawable1);
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        recycleBitmap();
    }

    //去掉缓存
    private List<String> changeUrl(List<String> urls) {
        //去掉"/thumb"
        List<String> realList = new ArrayList<>();
        if (urls != null) {
            if (urls.size() > 0) {
                for (int i = 0; i < urls.size(); i++) {
                    String s = urls.get(i);
                    if (s != null) {
                        if (s.contains("/thumb/")) {
                            String[] split = s.split("/thumb/");
                            String realUrl = split[0] + "/" + split[1];
                            realList.add(realUrl);
                            MyLogUtils.e(TAG, realList.get(i));
                        } else {
                            realList.add(urls.get(i));
                        }
                    }
                }
            }
        }
        return realList;
    }
}
